<?php
/**
 * hognyi @taoding 2018.11.19
 *
 *
 */
namespace App\Logic;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Resources\Agent as AgentResource;
use App\Models\Agent;
use App\Models\Linkman;
use App\Models\SysUser;
use PhpParser\Node\Stmt\TryCatch;
use Illuminate\Support\Facades\Hash;

class AgentLogic
{
	
	/**
	 * 表单数据
	 * @var array
	 */
	private $_post_data = array();
	
		
	public function __construct()
	{
		
	}
	
	// 分页获取代理商列表
	static public function getAgentList($where, $page = 1, $limit = 20)
	{
		
		return AgentResource::collection(Agent::where($where)->orderBy('sort', 'desc')->paginate($limit))->additional(['code' =>200,'status' => 'success']);

	}
	

	//获取客户详情
	static public function getCompanyDetail($id,$where){		
		//$company_info = Agent::with('linkman')->where($where)->first();
		try{
			$company_info = DB::table('at_enterprise_info')
			->leftJoin('at_linkman', 'at_enterprise_info.id', '=', 'at_linkman.at_enterprise_info_id')
			->leftJoin('sys_user', 'at_enterprise_info.id', '=', 'sys_user.company_id')
			->select('at_enterprise_info.*', 'at_linkman.linkman_name','at_linkman.linkman_phone','sys_user.login_name','sys_user.password','legal_person','legal_person_phone')
			->where('at_enterprise_info.id', '=', $id)
			->first();
		}catch (\Exception $e){
			echo $e->getMessage();
		}
		
		return $company_info;		
	}

    //更改代理商状态
    public static function companyState($id,$company_state){
        return DB::table('at_enterprise_info')
            ->where(['id'=>$id])
            ->update(['company_state'=>$company_state]);
    }

	//创建代理商	
	public function create($request){	
		$this->_post_data = $request->all();
		try {
			DB::beginTransaction();
			$company_info = $this->_create();
			return $company_info;
		} catch (\Exception $e) {
			DB::rollBack();
			return ['error' => $e->getMessage()];
		}						
	}
	
	public function _create(){
		//代理商
		$this->_post_data['at_time'] = date('Y-m-d H:i:s');
		$agent_insert['company_name'] = $this->_post_data['company_name'];
		$agent_insert['address'] = $this->_post_data['address'];			
		$agent_insert['company_type'] = $this->_post_data['company_type']; 		
		$agent_insert['balance'] = $this->_post_data['balance'];
		$agent_insert['ratio'] = $this->_post_data['ratio'];
		$agent_insert['bank_name'] = $this->_post_data['bank_name'];
		$agent_insert['bank_account'] = $this->_post_data['bank_account'];
		$agent_insert['create_by'] = \Auth::user()->name; //'hongyi';
		$agent_insert['company_state'] = 1 ;
		$agent_insert['del_flag'] = 0;
		$agent_insert['create_date'] = $agent_insert['update_date'] = $this->_post_data['at_time'];
		
		//联系人
		$linkman_insert['legal_person'] = $this->_post_data['legal_person'] ;
		$linkman_insert['legal_person_phone'] = $this->_post_data['legal_person_phone'];
		$linkman_insert['linkman_name'] = $this->_post_data['linkman_name']; 
		$linkman_insert['linkman_phone'] = $this->_post_data['linkman_phone']; 		
		$linkman_insert['create_date'] = $linkman_insert['update_date'] = $this->_post_data['at_time'];
		$linkman_insert['create_by'] = $linkman_insert['update_by'] = \Auth::user()->name;
		
		//用户
		$user_insert['login_name'] = $this->_post_data['login_name']; 
		$user_insert['password'] = Hash::make($this->_post_data['password']); 
        $user_insert['name'] = $user_insert['create_by'] = 'jfxt-'.\Auth::user()->name;
        $user_insert['update_by'] = 'jfxt-'.\Auth::user()->name;
        $user_insert['create_date'] = $user_insert['update_date'] = $this->_post_data['at_time'];

		try{
		      $agent_model = Agent::create($agent_insert); //创建agent
		}catch (\Exception $e){
		    echo $e->getMessage();
		}
		
		if (!$agent_model->id) {
		    throw new \Exception('代理商保存保存失败');
		}
		
		try{
		    $linkman_insert['at_enterprise_info_id'] = $agent_model->id;
		    $link_man_model = Linkman::create($linkman_insert); //创建 at_linkman
		}catch (\Exception $e){
		    echo $e->getMessage();
		}	
		if(!$link_man_model->id){
		    throw new \Exception('公司联系人保存失败');
		}
		
		try{
			$user_insert['company_id'] = $agent_model->id;
		    $user_insert['enterprise_marking'] = $agent_model->company_name;		    
		    $sys_user_model = SysUser::create($user_insert); //创建sys_user用户		    
		}catch (\Exception $e){
		    echo $e->getMessage();
		}		
		if(!$sys_user_model->id){
		    throw new \Exception('用户保存失败');
		}	
		
		if ($sys_user_model) {
			DB::commit();
			return $agent_model->toArray();
		} else {
			$this->pay_log('$agent_model.error' . var_export($agent_model, true));
			throw new \Exception('创建代理商失败');
		}
	}

    //更新密码
    public function password($request,$id){
        try{
            DB::beginTransaction();
            $agent_status = $this->_password($request,$id);
            return $agent_status;
        }
        catch(\Exception $e){
            echo $e->getMessage();exit;
            DB::rollBack();

            return ['error' => $e->getMessage()];
        }

    }
    //修改密码
    public function _password($request,$id){
        try{
            //更新用户
            $sys_user_where['company_id'] = $id;
            $sys_user_info = SysUser::where($sys_user_where)->first();
            $sys_user_info->login_name = $request->login_name;
            if(!empty($request->password)){
                $sys_user_info->password = Hash::make($request->password);
            }
            $sys_user_info->update_by = 'jfxt-'.\Auth::user()->name;
            $sys_user_action = $sys_user_info->save();
        }
        catch (\Exception $e){
            echo $e->getMessage();exit;
            DB::rollBack();
        }

        DB::commit();
        if($sys_user_action){
            return $sys_user_action;
        }
        else{
            return false;
        }
    }


	//更新代理商
	public function update($request,$id){ 
	    try{
	        DB::beginTransaction();
	        $agent_status = $this->_update($request,$id);  	   
    	    return $agent_status;
	    }
	    catch(\Exception $e){
	    	echo $e->getMessage();exit;
	        DB::rollBack();	        	        
	       
	        return ['error' => $e->getMessage()];	        
	    }
	    
	}
	
	public function _update($request,$id){
		$this->_post_data['at_time'] = date('Y-m-d H:i:s');
	    try{
    	    $agent = Agent::findOrFail($id);
    	    $agent_action = $agent->update([
    	        'company_name' => $request->company_name,
    	        'address' => $request->address,
    	        'company_type' => $request->company_type,
    	        'balance' => $request->balance,
    	        'ratio' => $request->ratio,
    	        'bank_name' => $request->bank_name,
    	        'bank_account' => $request->bank_account,
    	        'create_by' => 'jfxt-'.\Auth::user()->name,
    	        'company_state'=> 1,
    	        'update_date'=> $this->_post_data['at_time'],
                'company_state'=>$request->company_state
    	    ]);

	    }
	    catch (\Exception $e){
	       echo $e->getMessage();exit;
	    	return false;
	    }

	    if($agent_action){
		    try{
	            //更新联系人
	            $linkman_where['at_enterprise_info_id'] = $id;
	            $link_man_info = Linkman::where($linkman_where)->first();
	            $link_man_info->legal_person = $request->legal_person;
	            $link_man_info->legal_person_phone = $request->legal_person_phone;
	            $link_man_info->linkman_name= $request->linkman_name;
	            $link_man_info->linkman_phone = $request->linkman_phone;
	            $link_man_info->update_by = $request->update_by = 'jfxt-'.\Auth::user()->name;
	            $link_man_info->update_date = $this->_post_data['at_time'];
	            $linkman_action = $link_man_info->save();
		    }
		    catch (\Exception $e){
		        //echo $e->getMessage();
		    	return false;
		    }
            if ($linkman_action){
                return $agent_action;
            }else{
                return false;
            }
	    }
	    else{
	    	return fasle;
	    }
	}
	
	public function delete($id){
		if(!empty($id)){
			DB::beginTransaction();
			try{
				$agent_info = Agent::where(['id'=>$id])->first();
				if($agent_info['id']){
					$agetn_result = Agent::destroy($id);
				}
				if($agetn_result){
					$linkman_info = LinkMan::where(['at_enterprise_info_id'=>$id])->first();
					if($linkman_info['id']){
						$linkman_result = Linkman::destroy($linkman_info['id']);
					}
					if($linkman_result){
						$sys_user_info = SysUser::where(['company_id'=>$id])->first();
						if($sys_user_info['id']){
							$sysuser_result = SysUser::destroy($sys_user_info['id']);
						}
						if($sysuser_result){
							DB::commit();
						}
						else{
							return false;
						}
					}
				}
				
				if($agetn_result && $linkman_result &&$sysuser_result){
					return true;
				}
				else{
					return false;
				}
				
			}
			catch (\Exception $e){
				DB::rollBack();
				echo $e->getMessage();
			}
		}
		
	}
	
}
